from django.db import models
from django.urls import reverse
from django.contrib.auth import get_user_model
from datetime import date, timedelta

User = get_user_model()

class Tool(models.Model):
    """
    工具模型
    """
    name = models.CharField(max_length=128, unique=True, verbose_name='工具名称')
    description = models.TextField(null=True, blank=True, verbose_name='工具描述')
    version = models.CharField(max_length=32, null=True, blank=True, verbose_name='版本号')
    category = models.CharField(max_length=64, null=True, blank=True, verbose_name='分类')
    url = models.URLField(null=True, blank=True, verbose_name='工具链接')
    calibrated_date = models.DateField(null=True, blank=True, verbose_name='校准日期')
    owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='工具所有人')
    is_active = models.BooleanField(default=True, verbose_name='是否启用')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '工具'
        verbose_name_plural = '工具'
        ordering = ['-created_at']

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('tools:tool_detail', kwargs={'pk': self.pk})
    
    @property
    def expiration_date(self):
        """
        计算工具过期日期（校准日期+1年）
        """
        if self.calibrated_date:
            return self.calibrated_date + timedelta(days=365)
        return None
    
    @property
    def status(self):
        """
        获取工具状态：
        - 'valid': 有效期内
        - 'expiring_soon': 快过期（剩余不足1个月）
        - 'expired': 已过期
        """
        if not self.expiration_date:
            return 'valid'
            
        today = date.today()
        one_month_later = today + timedelta(days=30)
        
        if self.expiration_date < today:
            return 'expired'
        elif self.expiration_date <= one_month_later:
            return 'expiring_soon'
        else:
            return 'valid'
    
    @property
    def days_until_expiration(self):
        """
        计算距离过期还有多少天
        """
        if self.expiration_date:
            delta = self.expiration_date - date.today()
            return delta.days
        return None